package com.zany.net;

import com.google.gson.*;
import com.zany.net.dto.request.RequestEntity;
import com.zany.net.dto.response.ResponseEntity;
import com.zany.net.service.NetService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommunicationHandler {

    private Map<String, String> headerMap = new HashMap<String, String>();
    private Map<String, Object> returnHeaderMap = new HashMap<String, Object>();
    private Map<String, String> bodyMap = new HashMap<String, String>();
    private Map<String, String> returnBodyMap = new HashMap<String, String>();
    private List<Map<String, String>> returnBodyList = new ArrayList<Map<String, String>>();
    private static Log logger = LogFactory.getLog(CommunicationHandler.class);
    private ApplicationContext context;
    private String returnCode;


    private String beanName = null;

    private String jsonStr = null;

    private final String CONVERT = "_convert";
    private final String SERVICE = "service_";

    private RequestEntity requestEntity;


    private NetService netService;

    public CommunicationHandler(String jsonStr, ApplicationContext context) {
        this.context = context;
        logger.info("jsonStr = " + jsonStr);
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = parser.parse(jsonStr).getAsJsonObject();
        JsonElement headerElement = jsonObj.get(NetService.HEADER);
        JsonObject asJsonObject = headerElement.getAsJsonObject();
        String msgcd = asJsonObject.get(NetService.MSGCD).getAsString();
        this.beanName = SERVICE + msgcd;
        netService = (NetService) context.getBean(beanName);
        this.requestEntity = netService.convert(jsonObj);
    }

    public String hendler() {
        ResponseEntity handler = netService.handler(this.requestEntity);
        Gson resGson = new GsonBuilder().create();
        return resGson.toJson(handler);
    }
}
